<!--计划管理->需求计划->计划运算向导-->
<template>
    <div class="content-wrapper a-base-container">
        <div class="requisition-set-wrapper">
            <!--按钮-->
            <div class="btn-wrapper clearfix">
                <btns-wrapper @searchClick="searchClick" :showModel="showModel" :orderId="orderId" :voucherState="voucherState" :editMask="editMask" @printOrder="printOrder" @switchList="switchList" @submitServer="submitServer('mrp')" @clickEdit="clickEdit" @deleteOrder="deleteOrder('mrp')" @getIdByData="getIdByData" @auditClick="auditClick" @turnThePage="turnThePage" @syncOrder="syncOrder" @submitOrder="submitOrder" @exportDetail="exportDetail" :sourceCode="sourceCode">
                    <template slot="neworder">
                        <a-dropdown class="btns" key="new" style="display:block">
                            <a class="ant-dropdown-link" @click="e => e.preventDefault()">
                                <a-icon class="btns-icon" type="file-add" />
                                <div class="btns-text">新增
                                    <a-icon type="down" style="color:rgb(24,144,255);vertical-align:middle;" />
                                </div>
                            </a>
                            <a-menu slot="overlay">
                                <a-menu-item key="0">
                                    <a href="javascript:void(0)" @click="choiceChange(1)">从销售订单</a>
                                </a-menu-item>
                                <a-menu-item key="1">
                                    <a href="javascript:void(0)" @click="choiceChange(3)">从主生产计划</a>
                                </a-menu-item>
                            </a-menu>
                        </a-dropdown>
                    </template>

                    <template slot="yunsuan">
                        <span style="cursor:pointer;" @click="startOperation" v-if="permissions.includes('productionDemand:operation')">
                                <a-button type="primary" style=""><a-icon type="caret-right" />开始运算</a-button>
                            </span>
                    </template>
                </btns-wrapper>
            </div>
            <div ref="print" class="documents-wrapper" id="documents-wrapper">
                <h3 class="text-center">
                    {{voucherTitle}}
                </h3>
                <section v-show="showModel=='list'">
                    <!--列表-->
                    <dynamicList ref="dyList" :basePostData="basePostData" :sourceCode="sourceCode" @switchList="switchList" @dblclick="getIdByData" :reportCode="reportCodeList"></dynamicList>
                </section>
                <section class="demand-content" v-show="showModel=='order'">
                    <div><span class="audit-status" v-show="voucherState==0">待审核</span><span class="audit-status" v-show="voucherState==1 || voucherState==10">{{voucherState==1?'已审核':'关闭'}}</span></div>
                    <!-- <a-row :span="24" class="order-dynamic-form-wrapper">
                        <a-from>
                            <a-col :xs="grid.xs" :sm="grid.sm" :md="grid.md" :lg="grid.lg" :xl="grid.xl" :xxl="grid.xxl">
                                <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="单据编号：" :rules="[{ required: true, message:'',trigger:'input'}]">
                                    <a-input v-model="mrpCode"></a-input>
                                </a-form-model-item>
                            </a-col>
                            <a-col :span="6">
                                MRP运算方案：
                                <a-select style="width:150px;" placeholder="请选择运算方案" showSearch @focus="getList" @change="handleChangePlan">
                                    <a-select-option v-for="item in planList" :key="item.code + item.name" :value="item.id">
                                        ({{item.code}}){{item.name}}
                                    </a-select-option>
                                </a-select>
                            </a-col>
                            <a-col :span="6">
                                MRP运算状态：
                                未运算
                            </a-col>
                        </a-from>
                    </a-row>
                    <br />
                    <a-table :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }" :columns="columns" :customRow="customClick" :data-source="dataSource" :scroll="{ x: 1000, y: 800 }" :pagination="false" bordered>
                        <template v-for="col in slotArray" :slot="col" slot-scope="text, record ,index">
                            <div data-key="">
                                <editable-cell v-if="isRouterAlive" :checkType="checkType" :text="text" :col="col" :index="index" :record="record" :dataSource="dataSource" :unitsDataDetails="unitsDataDetails" :unitsAssistSelect="unitsAssistSelect" :dynamicAllData="dynamicFormData" :dynamicFormDataMap="dynamicFormDataMap" @change="onCellChange(index, col, $event)"  @choiceAddData="choiceAddData(index,col,$event,'mrp')" />
                            </div>
                        </template>
                    </a-table> -->
                    <a-form-model :layout="formLayout">
                        <div class="header-box">
                            <order-dynamic-form :FormData="orderHeaderData" :receiptNumber="receiptNumber" @changetime="onChangeTime" @clickItem="setValue"></order-dynamic-form>
                            <div class="edit-mask-header" v-show="editMask">
                                <!-- 遮罩（点击修改关闭遮罩） -->
                            </div>
                        </div>
                        <br/>
                        <div class="table-box">
                            <!-- 表的数据list表 llllll-->
                            <!-- :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }" -->
                            <a-table  :columns="columns" :customRow="customClick" :data-source="dataSource" :scroll="{ x: 1000, y: 347 }" :pagination="false" bordered>
                                <template v-for="col in slotArray" :slot="col" slot-scope="text, record ,index" >
                                    <div data-key="">
                                        <editable-cell v-if="isRouterAlive" :checkType="checkType" :text="text" :col="col" :index="index" :record="record" :dataSource="dataSource"  :unitsDataDetails="unitsDataDetails" :unitsAssistSelect="unitsAssistSelect" :dynamicAllData="dynamicFormData" :dynamicFormDataMap="dynamicFormDataMap" @change="onCellChange(index, col, $event)"  @choiceAddData="choiceAddData(index,col,$event,'mrp')" />
                                        <!-- <span v-if="text && col == 'sourceVoucherType'">
                                            <span v-if="text == 'MasterProductionSchedule'">主生产计划</span>
                                            <span v-if="text == 'SaleDelivery'">销售订单</span>
                                        </span> -->
                                    </div>
                                </template>
                                
                            </a-table>
                            <div class="edit-mask edit-mask-selection" v-show="editMask">
                                <!-- 遮罩（点击修改关闭遮罩） -->
                            </div>
                        </div>
                        <div class="footer-box">
                            <order-dynamic-form :FormData="orderFooterData" @downSelectChange="downSelectChange"  @changetime="onChangeTime" @clickItem="setValue"></order-dynamic-form>
                            <div class="edit-mask-footer" v-show="editMask">
                                <!-- 遮罩（点击修改关闭遮罩） -->
                            </div>
                        </div>
                    </a-form-model>
                </section>
            </div>
            
        </div>
        <drag-modal v-model="visibleTips" @cancel="cancel" @ok="ok" :title="'选择' + modalTitle" :width="1100">
            <p>{{modalTitle}}表头</p>
            <div style="min-height:230px">
                <a-table :columns="columnsChoiceHeader" :data-source="saleOrderMain" bordered :pagination="false" :row-selection="rowSelectionMain" :scroll="{x:1000,y:260}">
                </a-table>
            </div>

            <p class="margin-top-10">{{modalTitle}}明细</p>
            <div style="min-height:230px">
                <a-table :columns="columnsChoiceDetails" :data-source="saleOrderDetail" bordered :pagination="false" :row-selection="rowSelectionDetails" :scroll="{x:1000,y:260}">
                </a-table>
            </div>
            <template slot="footer">
                <div>
                    <a-button type="primary" @click="ok">确认</a-button>
                    <a-button @click="cancel" class="margin-left-10">关闭</a-button>
                </div>
            </template>
        </drag-modal>
        <a-modal :visible="startVisible" :closable="false">
            <a-row :span="24" :gutter="[8,16]">
                <a-col :span="24" :push="8">
                    <a-spin v-show="runNewPercentage <= 20 " />
                    <a-icon v-show="runNewPercentage > 20 " type="check" style="color:#87d068;font-size:18px;font-weight:bold;" /> 整理物料
                </a-col>
                <a-col :span="24" :push="8">
                    <a-spin v-show="runNewPercentage > 20 && runNewPercentage <= 40 " />
                    <a-icon v-show="runNewPercentage > 40 " type="check" style="color:#87d068;font-size:18px;font-weight:bold;" /> 查询可用量
                </a-col>
                <a-col :span="24" :push="8">
                    <a-spin v-show="runNewPercentage > 40 && runNewPercentage <= 60 " />
                    <a-icon v-show="runNewPercentage > 60 " type="check" style="color:#87d068;font-size:18px;font-weight:bold;" /> 执行可用量分配
                </a-col>
                <a-col :span="24" :push="8">
                    <a-spin v-show="runNewPercentage > 60 && runNewPercentage <= 80 " />
                    <a-icon v-show="runNewPercentage > 80 " type="check" style="color:#87d068;font-size:18px;font-weight:bold;" /> 生成运算结果
                </a-col>
                <a-col :span="24" :push="8">
                    <a-spin v-show="runNewPercentage > 80 && runNewPercentage < 100 " />
                    <a-icon v-show="runNewPercentage >= 100 " type="check" style="color:#87d068;font-size:18px;font-weight:bold;" /> 生成建议数据
                </a-col>
                <a-progress style="height:10px;" :strokeWidth="10" :stroke-color="{from: '#108ee9',to: '#87d068',}" :percent="runNewPercentage" status="active" />
            </a-row>
            <template slot="footer">
                <a-button @click="handleCancel">
                    关闭
                </a-button>
            </template>
        </a-modal>
    </div>
</template>
<script>

import pro from '@/mixins/procurement/pro'
import getDate from "@/utils/tool/date";
import { list, saleOrderList, startOper, planList, code,MRPcode, mrpSave, mrpDelete, mrpSubmit, mrpExamine } from "@/api/production/productionMRP";

import { mapState } from "vuex";
export default {
    mixins: [pro],
    data() {
        return {
            codes:[],//获取单据编号来源
            sourceCode: 'MrpOperation',
            showModel: 'order',
            checkType: 'is_made_self,is_made_request',//采购，生产，委外
            reportCodeList: 'ProductionPlan_List_Report',              //列表code
            //----------↓样式----------
            btnGrid: {
                xs: 2,
                sm: 2,
                md: 2,
                lg: 2,
                xl: 2
            },
            grid: {
                xs: 24,
                sm: 24,
                md: 12,
                lg: 8,
                xl: 8,
                xxl: 6
            },
            // formLayout: "inline",
            fromStyle: { paddingTop: "8px" },
            labelCol: { span: 6 },
            wrapperCol: { span: 10 },
            editFalse: {
                borderBottom: '1px solid #ded7d7'
            },
            //----------↑样式----------
            // editColumnArraya: [],//可编辑的字段
            isRouterAlive: true,
            mrpCode: null,
            planList: [],
            planId: null,
            visibleTips: false,
            columnsChoiceHeader: [{
                title: '序号',
                dataIndex: 'index',
                width: 40,
                customRender: (text, record, index) => {
                    return <span>{index + 1}</span>
                },
                align: 'center'
            }, {
                title: '单据编号',
                dataIndex: 'voucherCode'
            }, {
                title: '单据日期',
                dataIndex: 'voucherDate'
            }, {
                title: '客户名称',
                dataIndex: 'crmName'
            }, {
                title: '业务员',
                dataIndex: 'salesmanName'
            }, {
                title: '收款方式',
                dataIndex: 'receiveType'

            }, {
                title: '订金金额',
                dataIndex: 'earnestMoney'

            }, {
                title: '制单人',
                dataIndex: 'createUserName'
            }],
            columnsChoiceDetails: [{
                title: '序号',
                dataIndex: 'index',
                width: 40,
                customRender: (text, record, index) => {
                    return <span>{index + 1}</span>
                },
                align: 'center'
            }, {
                title: '物料编码',
                dataIndex: 'inventoryCode'
            }, {
                title: '物料名称',
                dataIndex: 'inventoryName'
            }, {
                title: '规格型号',
                dataIndex: 'inventorySpecification'
            }, {
                title: '主计量',
                dataIndex: 'baseUnitName'
            }, {
                title: '数量',
                dataIndex: 'baseQuantity',
            }, {
                title: '计划开始日期',
                dataIndex: 'planBeginDate'
            }, {
                title: '预计交货日期',
                dataIndex: 'deliveryDate'
            }],
            computedData: [],//选中数据显示数据

            value: null,
            saleOrder: false,
            productionPlan: false,
            modalTitle: '',

            saleOrderMain: [],//销售订单表头
            saleOrderDetail: [],//销售订单明细

            selectedRowKeysMain: [],
            selectedRowKeysDetails: [],
            selectedRowsDetails: [],//选中的明细

            startVisible: false,
            startComputedData: {},//开始运算传递的参数


            //===========开始运算字段============
            runPercentage: 0,//运行的百分比
            runNewPercentage: 0,//当前运行百分比
            selectedRowKeys: [],
            selectedRowKeysList: [],
            detailObj: {},
            // operationSwitchOpen: true
        }
    },
    computed: {
        rowSelectionMain() {
            return {
                columnWidth: 40,
                selectedRowKeys: this.selectedRowKeysMain,
                onChange: this.onSelectChangeMain
            }
        },
        rowSelectionDetails() {
            return {
                columnWidth: 40,
                selectedRowKeys: this.selectedRowKeysDetails,
                onChange: this.onSelectChangeDetails,
                getCheckboxProps: (record) => ({
                    props: {
                        disabled: true,
                    },
                }),
            }
        },
        ...mapState({
            userInfo: state => state.user.info,
            permissions: state => state.user.permissions,
            realName: state => state.user.name,
        }),
    },
    created() {
        this.getList();    
    },
    mounted() {
        // this.operationSwitchOpen = this.voucherState === 1 ? false : true
    },
    
    methods: {
        reload() {
            //强制刷新表格
            this.isRouterAlive = false;
            this.$nextTick(function () {
                this.isRouterAlive = true;
            });
        },
        getCode() {
            //获取方案编码
            MRPcode({dataSource: "MrpOperation"}).then((res) => {
                if (res.code == 200) {
                    this.receiptNumber = res.message;
                    this.mrpCode = res.message;
                    // this.voucherCode = res.message
                    for (let i = 0; i < this.orderHeaderData.length; i++) {
                        if (this.orderHeaderData[i].code == 'voucherCode') {
                            this.$set(this.orderHeaderData[i], 'onEdit', false)
                            this.$set(this.orderHeaderData[i], 'value', this.receiptNumber)
                        }
                        if (this.orderHeaderData[i].code == 'voucherDate') {
                            this.$set(this.orderHeaderData[i], 'value', getDate.getCurrentMoment().format('YYYY-MM-DD'))
                        }
                    }
                } else {
                    // this.$message.warning(res.message);
                }
            });
        },
        getList() {
            //获取方案
            let data = {
                current: 1,
                size: -1,
            }
            list(data).then(res => {
                if (res.code === 200) {
                    const { records } = res.data;
                    this.planList = records;
                }
            })
        },
        handleChangePlan(value) {
            //选择方案
            this.planList.forEach(list => {
                if (list.id == value) {
                    if (this.startComputedData.mrpData) {
                        //如果先选择单据来源在选择方案的话
                        list.mrpData = this.startComputedData.mrpData;
                    }
                    this.startComputedData = list;
                }
            });
        },
        choiceChange(v) {
            //单据来源，选单
            this.selectedRowKeysMain = [];
            this.selectedRowKeysDetails = [];
            if (v == 1) {
                // if (e.target.checked) {
                    //销售订单
                    saleOrderList().then(res => {
                        if (res.code === 200) {
                            this.visibleTips = true;
                            this.modalTitle = '销售订单';
                            this.saleOrder = true;
                            this.productionPlan = false;

                            if (res.data.saleOrderMain.length > 0) {
                                res.data.saleOrderMain.forEach(item => {
                                    item.key = item.id;
                                    item.sourceVoucherType = "销售订单"
                                });
                            }
                            if (res.data.saleOrderDetail.length > 0) {
                                res.data.saleOrderDetail.forEach(item => {
                                    item.key = item.id;
                                    item.voucherType = 1;//预算单据类型
                                    item.code = this.mrpCode;
                                    item.operationQuantity = item.baseQuantity;//运算数量
                                    item.voucherId = item.id;
                                    //item.sourceVoucherType = "SaleOrder"
                                    item.sourceVoucherType = "销售订单"
                                });
                            }
                            this.saleOrderMain = res.data.saleOrderMain;
                            this.saleOrderDetail = res.data.saleOrderDetail;
                        }
                    })
                // } else {
                //     this.saleOrder = false;
                //     this.selectedRowKeysMain = [];
                //     this.selectedRowKeysDetails = [];
                //     if (this.computedData.length > 0) {
                //         this.computedData = this.computedData.filter(item => item.voucherType != 1);

                //         this.$set(this.startComputedData, 'mrpData', this.computedData);
                //     }
                // }
            }
            if (v == 3) {
                //主生产计划
                // if (e.target.checked) {
                    planList().then(res => {
                        if (res.code === 200) {
                            this.visibleTips = true;
                            this.modalTitle = 'MPS主生产计划';
                            this.saleOrder = false;
                            this.productionPlan = true;

                            if (res.data.saleOrderMain.length > 0) {
                                res.data.saleOrderMain.forEach(item => {
                                    item.key = item.id;
                                });
                            }
                            if (res.data.saleOrderDetail.length > 0) {
                                res.data.saleOrderDetail.forEach(item => {
                                    item.key = item.id;
                                    item.voucherType = 3;//预算单据类型
                                    item.code = this.mrpCode;
                                    item.operationQuantity = item.baseQuantity;//运算数量
                                    item.voucherId = item.id;
                                    item.deliveryDate = item.planEndDate
                                    //item.sourceVoucherType = "MasterProductionSchedule"
                                    item.sourceVoucherType = "主生产计划"
                                });
                            }
                            this.saleOrderMain = res.data.saleOrderMain;
                            this.saleOrderDetail = res.data.saleOrderDetail;
                        }
                    })
                // } else {
                //     this.productionPlan = false;
                //     this.selectedRowKeysMain = [];
                //     this.selectedRowKeysDetails = [];
                //     if (this.computedData.length > 0) {
                //         this.computedData = this.computedData.filter(item => item.voucherType != 3);
                //         this.$set(this.startComputedData, 'mrpData', this.computedData);
                //     }
                // }
            }
        },
        onSelectChangeMain(keys, rows) {
            this.codes = rows;
            //选单表头table
            this.selectedRowKeysMain = keys;
            let detailsKeys = [];
            this.saleOrderDetail.forEach(d => {
                rows.forEach(r => {
                    if (d.orderId == r.id) {
                        detailsKeys.push(d.id,r.voucherCode);
                    }
                });
            });
            detailsKeys = [...new Set(detailsKeys)]
            this.selectedRowKeysDetails = detailsKeys;
            console.log(this.codes);
        },
        onSelectChangeDetails(keys, rows) {
            // this.codes=[...rows]
            //选单明细table
            this.selectedRowKeysDetails = keys;
            this.selectedRowsDetails = rows;
            //选中明细同时表头也要选中
            let mainKeys = [];
            rows.forEach(r => {
                mainKeys.push(r.orderId)
            });
            mainKeys = [...new Set(mainKeys)]
            this.selectedRowKeysMain = mainKeys;
        },
        onSelectChange(selectedRowKeys,rows) {
            this.selectedRowKeys = [...selectedRowKeys]
            let arr = []
            this.dataSource.forEach(i => {
                rows.forEach(j => {
                    if (i.id === j.id) {
                        arr.push(i)
                    }
                })
            })
            this.selectedRowKeysList = [...new Set(arr)]
        },
        cancel() {
            this.visibleTips = false;
        },
        
        //新增预测单
        newForecast () {
            this.showModel = 'order';
            this.editMask = false;
            this.loading = false;
            this.voucherState = -1;
            this.sourceVoucherData = {};//清空来源数据
            this.initForm(1);
        },

        ok() {
            this.selectedRowsDetails = [];
            this.saleOrderDetail.forEach(item => {
                this.selectedRowKeysDetails.forEach((details, index) => {
                    if (item.id == details) {
                        this.codes.forEach(it=>{
                            if(item.orderId == it.id){
                                this.selectedRowsDetails.push({...it,...item})
                            }
                        })
                    }
                })
            })
           
            //保存选中需要计算的明细
            if (this.selectedRowsDetails.length < 1) {
                this.$message.warning('请选中一条或多条数据');
                return
            } else {
                // 合并选中后的数组
                let arr3 = {} // 辅助数组

                let arr4 = this.selectedRowsDetails
                
                
                // let arr4 = this.selectedRowsDetails.reduce((sum, current) => {
                //     if (!arr3[current.voucherCode]) {// 如果不在
                //         arr3[current.voucherCode] = current.voucherCode //baseQuantity voucherCode
                //         sum.push(current)
                //     }
                //     return sum
                // }, [])
                this.computedData = arr4.map((item, index) => {
                    return {
                        ...item,
                        operationQuantity: item.baseQuantity,
                        operationNumber: item.baseQuantity,
                        number: index + 1,
                        baseUnitNumber: item.baseUnit,
                        baseUnit: item.baseUnitName,
                        sourceVoucherId : item.orderId,
                        sourceVoucherCode : item.voucherCode,
                    }
                });
                this.dataSource = this.computedData.map(item=>{
                    return {
                        ...item,
                        bussessPlanId: item.bussessPlan,
                        bussessPlan : item.bussessPlan == 1 ? "采购" : item.bussessPlan == 2 ? "自制" : item.bussessPlan  ? "委外" : "",
                        releaseState: item.releaseState == 1 ? "未下达" : item.releaseState == 2 ? "部分下达" : item.releaseState ? "全部下达" : "",
                        releaseStateId: item.releaseState,
                        needDate: item.deliveryDate,
                        planEndDate: item.deliveryDate,
                        sourceVoucherCode : item.voucherCode,
                    }
                })

                this.computedData.forEach(element => {
                    delete element.id;
                });

                //补足表格
                if (this.dataSource.length < this.dataSourceNumber) {
                    for (let i = this.dataSource.length; i < this.dataSourceNumber; i++) {
                        let array = {
                            number: i + 1,
                        };
                        this.dataSource.push(array);
                    }
                } 
                this.addTotal();//添加合计

                this.$set(this.startComputedData, 'mrpData', this.computedData);
                // this.startComputedData.mrpData = this.computedData
                this.editMask = false;
                this.voucherState = -1;
                this.visibleTips = false;
                this.showModel = 'order'
            }
            this.orderHeaderData.forEach(element=>{//表头
                if(element.name == "运算时间" && element.code == "operationDate"){
                    element.value = ""
                }
                if(element.name == "单据日期" && element.code == "voucherDate"){
                    element.value = newData()
                }
                if(element.name == "单据编号" && element.code == "voucherCode"){
                    element.value = ""
                }
                if(element.name == "MRP运算方案" && element.code == "chooseSchemeId"){
                    element.value = ""
                }
                if(element.name == "运算状态"){
                    element.value = 0
                }
                if(element.name == "单据状态" && element.code == "voucherState"){
                    element.value = -1
                }
            })
            this.orderFooterData.forEach(item => {//表尾
                if(item.name == "审核人" || item.name == "审核日期"){
                    item.value = "";
                }
                if(item.name == "创建日期" && item.code == "createDate"){
                    item.value = new Date().getFullYear() + '-' + (new Date().getMonth() + 1) + "-" + new Date().getDate();
                }
                if(item.name == "创建人" && item.code == "createUserId"){
                    item.value = this.realName
                }
            })
            function newData() {
                let d = new Date();
                let year = d.getFullYear();
                let month = '' + (d.getMonth() + 1);
                let day = '' + d.getDate();
                if (month.length < 2) month = '0' + month;
                if (day.length < 2) day = '0' + day;
                let SendedTimes = year + '-' + month + '-' + day
                return SendedTimes
            }
            this.voucherState = -1;
            this.getCode()
        },
        startOperation() {
            //开始运算
            this.runNewPercentage = 0;
            if(+this.voucherState !== 1) return this.$message.warning('单据未审核，不能运算');
            this.startComputedData = {
                id: this.detailObj.id,
                mrpData: this.dataSource.filter(k=>k.id).map(item => {
                    return {
                        ...item,
                        operationQuantity: item.baseQuantity,
                        operationNumber: item.baseQuantity,
                        baseUnit: item.baseUnit_temp_id,
                    }
                }),
            }
            if (!this.startComputedData.id) {
                this.$message.warning('请选择MRP运算方案');
                return;
            }

            let reportData = JSON.parse(JSON.stringify(this.startComputedData.mrpData));

            if (!reportData) {
                this.$message.warning('请选择单据来源');
                return;
            }

            if (reportData.length < 1) {
                this.$message.warning('请选择单据来源');
                return;
            }

            for (let i = 0; i < reportData.length; i++) {
                if (reportData[i].operationQuantity == null || reportData[i].operationQuantity == '') {
                    this.$message.warning('运算数量必须填写');
                    return;
                }
            }

            this.startVisible = true;
            let timer = setInterval(() => {
                this.runNewPercentage += Math.round(Math.random());
                if (this.runNewPercentage >= 98) {
                    clearInterval(timer)
                }
            }, 50)

            startOper(this.startComputedData).then(res => {
                if (res.code === 200) {
                    this.runNewPercentage = 100;
                    this.clerarData();
                    setTimeout(() => {
                        this.handleCancel();
                        let data = res.data.map((element,index)=> {
                            return {
                                ...element,
                                
                                // baseUnit: element.baseUnit,
                                // baseUnitNumber: element.baseUnit,
                                baseUnit : element.baseUnitName,
                                baseUnitId : element.baseUnit,
                                bussessPlanId : element.bussessPlan,
                                bussessPlan : element.bussessPlan == 1 ? "采购" : element.bussessPlan == 2 ? "自制" : element.bussessPlan ? "委外" : "",
                                releaseStateId: element.releaseState,
                                releaseState: element.releaseState == 1 ? "未下达" : element.releaseState == 2 ? "部分下达" : element.releaseState ? "全部下达" : "",

                            }
                        })

                        if(this.saleOrderDetail.length > 1){
                            for (let i in this.saleOrderDetail) {
                                if(this.saleOrderDetail[i].sourceVoucherType == "SaleOrder"){
                                    data.createUserName = "销售订单";
                                    data.createUserId += this.saleOrderDetail[i].id + ",";
                                    data.datasource = "SaleOrder"
                                    break
                                }
                                if(this.saleOrderDetail[i].sourceVoucherType == "MasterProductionSchedule"){
                                    data.createUserName = "主生产计划";
                                    data.createUserId += this.saleOrderDetail[i].id + ",";
                                    data.datasource = "MasterProductionSchedule"
                                    break
                                }
                            }
                            if(data.createUserId){
                                data.createUserId = data.createUserId.substring(0, data.createUserId.length - 1)
                            }
                        } else {
                            for (let i in this.dataSource) {
                                if(this.dataSource[i].sourceVoucherType == "销售订单"){
                                    data.createUserName = "销售订单";
                                    data.createUserId += this.dataSource[i].id + ",";
                                    data.datasource = "SaleOrder"
                                    break
                                }
                                if(this.dataSource[i].sourceVoucherType == "主生产计划"){
                                    data.createUserName = "主生产计划";
                                    data.createUserId += this.dataSource[i].id + ",";
                                    data.datasource = "MasterProductionSchedule"
                                    break
                                }
                            }
                            if(data.createUserId){
                                data.createUserId = data.createUserId.substring(0, data.createUserId.length - 1)
                            }
                        }
                        
                        this.$store.commit('SET_MRP', data);

                        this.$router.push({
                            // path: '/production/productionAdvice',
                            path:'/production/management/productionOrder',
                            query:{
                                numbers:4
                            }
                        })
                    }, 200);
                }
            }).catch(err => {
                // this.$message.error(err);
                this.handleCancel();
            })
            this.orderHeaderData.forEach(element=>{
                if(element.name == "运算时间" && element.code == "operationDate"){
                    element.value = newData()
                }
            })
            function newData() {
                let d = new Date();
                let year = d.getFullYear();
                let month = '' + (d.getMonth() + 1);
                let day = '' + d.getDate();
                if (month.length < 2) month = '0' + month;
                if (day.length < 2) day = '0' + day;
                let SendedTimes = year + '-' + month + '-' + day
                return SendedTimes
            }

        },
        clerarData() {
            //清空所有数据
            this.startComputedData = {id: '', mrpData: []};
            // this.startComputedData.mrpData = [];
            this.computedData = [];//列表
            this.saleOrder = false;
            this.productionPlan = false;
            // this.operationSwitchOpen = true;
            this.saleOrderMain = [];//销售订单表头
            this.saleOrderDetail = [];//销售订单明细

            this.selectedRowKeysMain = [];
            this.selectedRowKeysDetails = [];
        },
        handleCancel() {
            //运算弹窗关闭
            this.startVisible = false;
        },

        submitServer(type) {
            const { dataSource, orderHeaderData, orderFooterData, dynamicFormData } = this;
            //拿出表头、表尾自定义字段
            let customField = dynamicFormData.filter(item => {
                return item.dataType != 1 && (item.dataTab == '表头' || item.dataTab == '表尾');
            })
            //在 深拷贝 前 处理dataSource中的 下拉选择
            dynamicFormData.forEach(element => {
                if (element.columnType == '下拉选择') {
                    dataSource.forEach((item, key) => {
                        item[element.code] = item[element.code + 'Id']
                    })
                }
            });
            let d = {
                detail: _.cloneDeep(dataSource),
                header: orderHeaderData.filter(item => { return item.dataType == 1 }),
                footer: orderFooterData.filter(item => { return item.dataType == 1 }),
                customField: customField,
            }
            //文字转换为id
            for (const key in d.detail) {
                d.detail[key].baseUnit_temp_id ? d.detail[key].baseUnit = d.detail[key].baseUnit_temp_id : '';//主计量
                d.detail[key].subUnit_temp_id ? d.detail[key].subUnit = d.detail[key].subUnit_temp_id : '';//辅计量
            }
            //设置日期默认值
            for (const key in d.header) {
                if (d.header[key].columnType == '日期' && d.header[key].value == '') {
                    d.header[key].value = getDate.getCurrentMoment().format('YYYY-MM-DD');
                }
            }
            //过滤自定义字段
            let defineData = dynamicFormData.filter(item => item.dataType != 1);
            let requestData = this.submitRegData(d, defineData);
            for (const key in orderHeaderData) {
                if (orderHeaderData[key].columnType == '搜索选择') {
                    //用于页面展示 新增...Name字段
                    if (orderHeaderData[key].code.indexOf('Id') != '-1') {
                        let tempname = orderHeaderData[key].code.substring(0, orderHeaderData[key].code.length - 2) + 'Name';

                        this.$set(requestData, tempname, orderHeaderData[key].valueName);
                        this.$set(requestData, orderHeaderData[key].code, orderHeaderData[key].valueId);
                    }
                }
            }
            if (this.orderId) {
                this.$set(requestData, 'id', this.orderId);
            }
            //必填判断
            let headerAndFooterVerify = this.onFillData.filter(item => item.dataTab == '表头' || item.dataTab == '表尾');
            if (this.headerInWherehouse) {//隐藏表头的仓库字段 同时去除必填 控制
                headerAndFooterVerify.forEach((element, index) => {
                    if (element.code == 'warehouseId') {
                        headerAndFooterVerify.splice(index, 1); //删除下标为i的元素
                    }
                });
            }

            if (this.headerInVendorName) {//隐藏表头的供应商字段 同时去除必填 控制
                headerAndFooterVerify.forEach((element, index) => {
                    if (element.code == 'vendorId') {
                        headerAndFooterVerify.splice(index, 1); //删除下标为i的元素
                    }
                });
            }
            if (this.headerInCrmName) {//隐藏表头的客户字段 同时去除必填 控制
                headerAndFooterVerify.forEach((element, index) => {
                    if (element.code == 'crmId') {
                        headerAndFooterVerify.splice(index, 1); //删除下标为i的元素
                    }
                });
            }
            if (this.isHideDetailsProductId) {//强制去掉  表头  加工产品名称和加工产品编码
                headerAndFooterVerify.forEach((element, index) => {
                    if (element.code == 'productId') {
                        headerAndFooterVerify.splice(index, 1); //删除下标为i的元素
                    }
                });

                headerAndFooterVerify.forEach((element, index) => {
                    if (element.code == 'productCode') {
                        headerAndFooterVerify.splice(index, 1); //删除下标为i的元素
                    }
                });
            }
            for (const key in requestData) {//表头和表尾的必填判断
                for (const onkey in headerAndFooterVerify) {
                    //console.log(requestData, headerAndFooterVerify, 'headerAndFooterVerify')
                    if (key != 'orderDetailList' && headerAndFooterVerify[onkey].code == key && !headerAndFooterVerify[onkey].value && headerAndFooterVerify[onkey].value !== 0) {
                        this.$message.warning(`${headerAndFooterVerify[onkey].name}必须填写!`)
                        return;
                    }
                }
            }
            let detailVerify = this.onFillData.filter(item => item.dataTab == '明细' && item.onEdit)
            let b = requestData.orderDetailList;
            //去掉明细当中工序的必填
            if (this.isDetailRecord) {
                detailVerify = detailVerify.filter(item => item.code != 'procedureId');
            }
            for (const key in b) {//明细的必填判断
                let a = b[key];
                for (const onkey in detailVerify) {
                    //console.log(a[detailVerify[onkey].code])
                    if (this.sourceCode == 'PeriodStartOfStock' && !a[detailVerify[onkey].code]) {
                        //库存期初判断 数量为0 也可以保存
                    } else {
                        if (!a[detailVerify[onkey].code] && a[detailVerify[onkey].code] != 0) {
                            this.$message.warning(`${detailVerify[onkey].name}必须填写!`)
                            return;
                        }
                    }
                }
            }
            this.submitServers()
        },

        //保存
        submitServers(){
            const params = {
                businessType: this.detailObj.businessType,
                crateDate: this.detailObj.crateDate,
                voucherCode: this.orderHeaderData.find(item => item.code === 'voucherCode').value,
                voucherState: this.detailObj.voucherState,
                voucherDate: this.orderHeaderData.find(item => item.code === 'voucherDate').value,
                //chooseSchemeId: this.orderHeaderData.find(item => item.code === 'chooseSchemeId').valueId,
                chooseSchemeName: this.orderHeaderData.find(item => item.code === 'chooseSchemeId').value,
                operationState: this.orderHeaderData.find(item => item.code === 'operationState').value,
                operationDate: this.orderHeaderData.find(item => item.code === 'operationDate').value,
                // sourceVoucherCode: this.orderHeaderData.find(item => item.code === 'sourceVoucherCode').valueId,
                // reviewerUserId: this.orderFooterData.find(item => item.code === 'reviewerUserId').valueId,
                // reviewerUserName: this.orderFooterData.find(item => item.code === 'reviewerUserName').value,
                reviewerDate: this.orderFooterData.find(item => item.code === 'reviewerDate').value,
                //voucherState: this.orderFooterData.find(item => item.code === 'voucherState').value,
                //id: this.orderId,
                // "sourceVoucherId" : this.dataSource.filter(k => k.inventoryCode).map(item=>{
                //     return item.orderId
                // }),
                "maMrpOperationDetailList": this.dataSource.filter(k => k.inventoryCode).map(item=>{
                    return {
                        ...item,
                        bussessPlan: item.bussessPlanId,
                        baseUnit: item.baseUnitNumber,
                        releaseState: item.releaseStateId,
                        schedulingStatus: item.schedulingStatusId,
                        sourceVoucherId : item.orderId,
                        sourceVoucherType : item.sourceVoucherType
                    }
                }),
            }
            params.createUserId = this.$store.state.user.info.id
            params.createUserName = this.$store.state.user.info.name
            params.dataSource = "MrpOperation"
            mrpSave(params).then(res => {
                if(res.code === 200) {
                    this.$message.success('保存成功')
                    this.editMask = true;
                    this.isSaveRun = true;
                    //this.$set(backData, 'voucherState', -1)
                    //this.getCode()
                    //if (!this.orderId) {
                        this.getIdByData(); //获取最新一条数据
                    //}
                } else {
                    this.$message.warning('保存失败')
                    this.computedData = []
                    this.isSaveRun = true;
                }
            })
        },

        //单据提交
        submitOrder (type) {
            let data = {
                id: this.orderId,
                status: type,//状态 -1:撤回提交,0:提交
            }
            if (!this.orderId) {
                this.$message.warning('该单据未保存不需要提交');
                return;
            }
            if (this.voucherState == -1 && type == -1) {
                this.$message.warning('该单据未提交无需撤回提交');
                return;
            }
            mrpSubmit(data).then(res => {
                if (res.code === 200) {
                    if (type == 0) {
                        this.$message.success('提交成功');
                    } else {
                        this.$message.success('撤回提交成功');
                    }
                    this.getIdByData();
                }
            })
        },
        //审核
        auditClick (type) {
            let requestData = {
                id: this.orderId,
                status: type
            }
            mrpExamine(requestData).then((response) => {
                if (response.code === 200) {
                    const backData = response.data;
                    if (type == 1) {
                        this.$message.success('审核成功');
                        // this.operationSwitchOpen = false
                        this.getIdByData();
                    }
                    if (type == 0) {
                        this.$message.success('弃审成功');
                        // this.operationSwitchOpen = true
                        this.getIdByData();
                    }
                } else {
                    // this.$message.warning(response.message);
                }
            })
        },
        //删除
        mapRemove (postData) {
            mrpDelete(postData).then(response => {
                if (response.code === 200) {
                    this.$message.success('删除成功');
                    this.orderId = '';
                    this.voucherState = 0;
                    this.getIdByData();//获取最新一条数据
                } else {
                    this.$message.error(response.message);
                }
            })
        },
        destroyed() {
            this.orderId = ''
            // this.operationSwitchOpen = false
        },
    },
}
</script>
<style lang="less">
@import "~@/style/purchase/voucher.less";
.demand-content {
    padding: 10px;
    height: calc(100% - 45px);
    font-size: 14px;
    color: rgba(0, 0, 0, 0.65);
    overflow-y: auto;
    .ant-form-inline .ant-form-item {
        display: block;
    }
    .order-dynamic-form-wrapper {
        margin-top: 20px;
        label:not(.form-check-label):not(.custom-file-label) {
            font-weight: normal;
        }
        .ant-form-item-label,
        .ant-form-item-control {
            line-height: 32px;
        }
        .ant-form-item {
            margin-bottom: 0;
        }
    }
    .header-box {
        display: fixed;
    }
}
</style>

